#include "key.h"
#include "led.h"
#include "s3c24xx.h"
#include "interrupt.h"
#include "stdio.h"

static void handle_irq_key(int irq, int exirq) {
    printf("handle_irq_key %d %d\n\r", irq, exirq);
    int keydat = GPFDAT;
    if(irq == 0) { //eint0  led4
		if (keydat & (1<<0)) {//k4 松开
			handle_led(4, 0);
		} else { /* 按下 */
			handle_led(4, 1);
		}
    } else if(irq == 1) { //led1
		if (keydat & (1<<1)) {//k1 松开 led0 off
			handle_led(1, 0);
		} else { /* 按下 */
			handle_led(1, 1);
		}
    } else if(irq == 2) { //led3
		if (keydat & (1<<2)) {//k3 松开
			handle_led(3, 0);
		} else { /* 按下 */
			handle_led(3, 1);
		}
    } else if(irq == 4) {
        if (exirq & (1<<4)) {/* eint4 */
            if (keydat & (1<<4)) {//k2 松开 led2
                handle_led(2, 0);
            } else { /* 按下 */
                handle_led(2, 1);
            }
        }
    }
}


static void key_init() {
    GPFCON &= ~((3<<0) | (3<<(1*2)) | (3<<(2*2)) | (3<<(4*2))); //清零
    GPFCON |= 2<<(0*2) | 2<<(1*2) | 2<<(2*2) | 2<<(4*2);  //设置为中断引脚
    GPFDAT |= (1 << 0) | (1 << 1) | (1 << 2 ) | (1 << 4);
    EXTINT0 |= 7<<(0*4) | 7<<(1*4) | 7<<(2*4) | 7<<(4*4); /* 设置中断触发方式: 双边沿触发 */
    EINTMASK &= ~(1<<4); //使能EINT4,  EINT0~3m默认enable

    register_irq(0, handle_irq_key);
    register_irq(1, handle_irq_key);
    register_irq(2, handle_irq_key);
    register_irq(4, handle_irq_key);
} 

void test_key() {
    printf("start test_key\n\r");
    led_init();
    key_init();
    while(1) ;
}
